/*
 * TextPacketQueue.cpp
 *
 *  Created on: 2018年8月13日
 *      Author: zhengboyuan
 */

#include "TextPacketQueue.h"

namespace av
{

TextPacketQueue::TextPacketQueue():
	m_maxSize(MAX_QUEUE_SIZE)
{
}

TextPacketQueue::~TextPacketQueue()
{
}

void TextPacketQueue::clear()
{
	comn::AutoCritSec lock(m_cs);
	m_packets.clear();
}

size_t TextPacketQueue::size()
{
	comn::AutoCritSec lock(m_cs);
	return m_packets.size();
}

bool TextPacketQueue::empty()
{
	comn::AutoCritSec lock(m_cs);
	return m_packets.empty();
}

size_t TextPacketQueue::push(AVPacketPtr& packet)
{
	comn::AutoCritSec lock(m_cs);

	if (!packet)
	{
		return m_packets.size();
	}

	m_packets.push_back(packet);

	return m_packets.size();
}

AVPacketPtr TextPacketQueue::pop()
{
	AVPacketPtr pkt;
	comn::AutoCritSec lock(m_cs);
	if (m_packets.size() > 0)
	{
		pkt = m_packets.front();
		m_packets.pop_front();
	}
	return pkt;
}

AVPacketPtr TextPacketQueue::pop(int64_t pts)
{
	AVPacketPtr pkt;
	comn::AutoCritSec lock(m_cs);
	if (m_packets.size() > 0)
	{

	}
	return pkt;
}

bool TextPacketQueue::pop(int64_t pts, AVPacketPtr& pkt)
{
	bool found = false;
	comn::AutoCritSec lock(m_cs);
	if (m_packets.size() > 0)
	{
		AVPacketPtr& frontPkt = m_packets.front();
		if (isMatched(frontPkt, pts))
		{
			pkt = frontPkt;
			m_packets.pop_front();
			found = true;
		}
	}
	return found;
}

bool TextPacketQueue::isMatched(AVPacketPtr& pkt, int64_t pts)
{
	if (pkt->pts <= pts)
	{
		return true;
	}

	return m_packets.size() >= m_maxSize;
}

void TextPacketQueue::setMaxSize(size_t maxSize)
{
	if (maxSize > 1)
	{
		m_maxSize = maxSize;
	}
}

bool TextPacketQueue::popUntil(int64_t pts, AVPacketPtr& pkt)
{
	bool found = false;
	comn::AutoCritSec lock(m_cs);
	while (m_packets.size() > 0)
	{
		AVPacketPtr& frontPkt = m_packets.front();
		if (frontPkt->pts <= pts)
		{
			pkt = frontPkt;
			m_packets.pop_front();
			found = true;
		}
		else
		{
			break;
		}
	}
	return found;
}



} /* namespace av */
